package com.clei.utils.helper;

import com.clei.utils.PrintUtil;

/**
 * 耗时记录器
 *
 * @author Y
 * @date 2023-09-18
 **/
public class TimeRecorder {
    /**
     * 指针
     */
    private int pointer;

    /**
     * 时刻list
     */
    private final long[] timeArr;

    /**
     * 阶段名称list
     */
    private final String[] rangeNameArr;

    /**
     * 构造
     * 初始化
     */
    public TimeRecorder() {
        this(8);
    }

    /**
     * 构造
     * 初始化
     */
    public TimeRecorder(int ranges) {
        this.timeArr = new long[ranges + 1];
        this.rangeNameArr = new String[ranges];
        this.timeArr[this.pointer++] = System.nanoTime();
    }

    /**
     * 记录
     */
    public void record() {
        record(curRangeName());
    }

    /**
     * 记录
     *
     * @param rangeName 区间名称
     */
    public void record(String rangeName) {
        this.timeArr[this.pointer++] = System.nanoTime();
        this.rangeNameArr[this.pointer - 2] = rangeName;
    }

    /**
     * 记录并打印当前阶段耗时
     */
    public void recordAndPrint() {
        recordAndPrint(curRangeName());
    }

    /**
     * 记录并打印当前阶段耗时
     *
     * @param rangeName 区间名称
     */
    public void recordAndPrint(String rangeName) {
        record(rangeName);
        PrintUtil.log("{}耗时：{}ms", rangeName,
                (this.timeArr[this.pointer - 1] - this.timeArr[this.pointer - 2]) / 1000000D);
    }

    /**
     * 打印总的信息
     */
    public void printAll() {
        int ranges = this.pointer - 1;
        for (int i = 0; i < ranges; i++) {
            String rangeName = this.rangeNameArr[i];
            PrintUtil.log("{}耗时：{}ms", rangeName, (this.timeArr[i + 1] - this.timeArr[i]) / 1000000D);
        }
        PrintUtil.log("开始时刻：{}, 结束时刻：{}, 总耗时：{}ms", this.timeArr[0], this.timeArr[ranges],
                (this.timeArr[ranges] - this.timeArr[0]) / 1000000D);
    }

    /**
     * 当前阶段名称
     *
     * @return 当前阶段名称
     */
    private String curRangeName() {
        return "区间" + this.pointer;
    }
}
